CHICIO CODING

Dirty clean code. Creative Stuff. Stuff.

How to calculate the reflection vector

In this post I will talk about reflection vector used in some lighting models, for example the Phong reflection model. I will show you how this vector is calculated.


In a previous post I talked about the Phong lighting model. I described all the different components contained inside it and how they try to describe and simulate different kind of light components. In particular you will remember that there’s a specular component that try to simulated the light reflected in a specific direction: the reflection direction. In the shader implementation this direction has been calculated using a GLSL method reflect:

vec3 reflectionDirection = reflect(-lightDirection, normalInterp);

Easy, isn’t it? But the most curios of you may asking: “How the f*$k this method calculate this reflection direction?” :stuck_out_tongue_closed_eyes:
We will suppose as in the previous post about the phong model that all vectors are normalized. Let’s start from the beginning. The formula to calculate the reflection direction is:

How is this formula obtained? Let’s start from a picture that represents our reflection vector and the other vectors used in the calculation.

Model view presenter ios unit tests

Before we start with the demonstration we also need to know what is the law of reflection:

The incident light ray L, the reflected ray R, and the normal N to the surface of the mirror all lie in the same plane. The angle of reflection $\Theta_R$ is equal to the angle of incidence of light $\Theta_L$. Both angles are measured with respect to the normal to the mirror. The reflected ray and the incident ray are on the opposite sides of the normal.

Now we are ready for our demonstration :sunglasses:.
From the law of refraction reported above we know that:

This equation could be rewritten as the dot product of the reflection direction with the normal equals the dot product of the incident light direction and the normal (remember that the dot product of two vector is equal to the cosine of the angle between them). So we have:

From the image above it’s also evident for symmetry that:

As you can see again from the image above, this two vectors could be easily calculated. In fact the first one is the difference between the reflection vector and the projection of it on the normal. The second one is the difference between the light incident vector and the projection of it on the normal. So for the reflection side we could write:

For the light side we could write:

As a consequence we obtain the following equation:

Now we can see again from the image above that the vector projections ${\hat {N}^{\prime}}$ and ${\hat {N}^{\prime \prime}}$ are equals, that means we could change the previous equation by substituting the first one with the second one. So we obtain the following equation:

Now we have all we need to calculate our R vector:

That’s it!! We get our formula. Now you’re ready to explain in detail the entire “magic” of the Phong model :relaxed:.

Model View Presenter on iOS: no more excuses, write your unit test

In this post I will talk about the model view presenter architectural pattern and how it can improve you unit test and your TDD workflow when developing an iOS application.


Unit test in iOS application is in some way “hard”. The architectural pattern implemented by default on iOS is the Model View Controller. This architecture provides you a clear separation between the UI and the business logic. The problem is that most of the time you have to fight with “Massive View Controllers” that act as glue between the model and a lot of UI/view code and that, for this reason, are not so easy to test. This basically means that most of the time the presentation logic, how the business model is displayed to the user in the User Interface, is tested in the wrong way, or maybe worst it is not tested.
This is were the Model View Presenter could save us. In this architectural pattern all the presentation logic is moved from the view controller to a new component, the presenter. This means that it will manage model objects to retrieve the data and then prepare it to be displayed by the view, that will be our View Controller. This one becomes a passive interface that has the only responsibility to show data returned by the presenter in the specific platform User Interface component. In this way the presenter is a component without any platform specific dependency, that works only on the view and other model objects, injected at construction time. In this way all dependencies could be mocked and you can unit test basically everything!! :relaxed:
Now it’s time to see the Model View Presenter in action!! :grin: We will create a simple app that shows a list on products in a UITableView. On the tap of a cell the product detail is shown. An error will be displayed if an error occurs when the products are retrieved or when it doesn’t contain all the data needed to show its detail.
We will develop this app using Test Driven Development technique, and I will show the unit tests created for each class implemented. These unit tests will also be written using the “Given-then-when” structure, typically used in Behaviour Driven Development. Even if not related to this article, I like this way of writing unit tests because they are more expressive, so I will use it in all my code. Below you can find a mockup of what we want to achieve.

Model view presenter mockup

Let’s start by creating a Product struct that we will use to describe our products. Each product will be composed of a name, a description and an image (identified by its name):

public struct Product {
    let name: String
    let description: String
    let image: String
    
    public init(name: String, description: String, image: String) {
        self.name = name
        self.description = description
        self.image = image
    }
}

The products objects will be retrieved using a Repository. First of all we need to define a Repository protocol. Generally speaking, we will try to define a protocol for all our classes so that we can work using abstraction (and not concrete implementation) to obtain the highest decoupling between our classes. Last but not least (and maybe the most important thing) by using protocols we will be able to produce some mocks/spies of our components in our unit tests.

public protocol Repository {
    func get(finish: @escaping ([Product]?) -> Void)
}

In our case the repository will not retrieve the data from a real datasource or using a service. All data will be retrieved from a local array inside the repository. This is the final implementation of our repository:

public class ProductsRepository: Repository {
    
    public func get(finish: @escaping ([Product]?) -> Void) {
        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(3000)) {
            let products = [
                Product(name: "Car", description: "A beautiful car", image: "car"),
                Product(name: "Book", description: "", image: "book")
            ]
            finish(products)
        }
    }
}

Even if out of our scope, below you can find the unit tests for our ProductsRepository. They are interesting because you can find an example of unit test with expectation (another thing to be discussed sooner or later :stuck_out_tongue_winking_eye:).

class ProductsRepositoryTests: XCTestCase {
    private var productsRepository: ProductsRepository!
    
    func testProductsRetrieved() {
        givenAProductsRepository()
        whenTheRepositoryTryToRetrieveProducts { [unowned self] products, repositoryExpectation in
            self.thenTheProductsListIsRetrieved(products: products,
                                                expectation: repositoryExpectation)
        }
        thenTheRepositoryFinishedToTryToRetrieve()
    }
    
    private func givenAProductsRepository() {
        productsRepository = ProductsRepository()
    }
    
    func whenTheRepositoryTryToRetrieveProducts(finish: @escaping ([Product]?, XCTestExpectation) -> Void) {
        let repositoryExpectation = expectation(description: "RepositoryExpectation")
        productsRepository.get { products in
            finish(products, repositoryExpectation)
        }
    }
    
    private func thenTheProductsListIsRetrieved(products: [Product]?, expectation: XCTestExpectation) {
        XCTAssertNotNil(products)
        XCTAssertTrue(products!.count > 0)
        expectation.fulfill()
    }
    
    private func thenTheRepositoryFinishedToTryToRetrieve() {
        waitForExpectations(timeout: 10) { error in
            if let error = error {
                XCTFail("Repository finish() not called: \(error)")
            }
        }
    }
}

Now it’s time to develop our ProductsPresenter presenter. It will need a view to which it will delegate the real user interface operation and the Repository to retrieve the products data. It will be responsible to manage:

  • the start of the view in the onStart() method. In this method we will have to update the view to show a loading status (that will be a UIActivityIndicator in the view implementation), then try to retrieve the products from the repository and show them on the view if everything goes fine. If something goes wrong show on the view an error message. In any case, it also need to hide the loading status after the retrieve operation has been completed.
  • the show detail action in the onSelected(product: Product) method. In this method we will have to check if all the product data is correct, that in our case means that the product must have a valid product. If it is valid, show its detail in the view, else an error message.

We start by defining the protocol ProductView, that contains all the valid operation of the view that our presenter will use:

public protocol ProductsView: class {
    func showLoadingStatus()
    func hideLoadingStatus()
    func show(title aTitle: String)
    func show(products: [Product])
    func showErrorWith(message: String)
    func showDetailFor(product: Product)
}

Now we are ready to proceed with the ProductsPresenter implementation:

public class ProductsPresenter {
    private unowned let productsView: ProductsView
    private let productsRepository: Repository
    
    public init(productsView: ProductsView, productsRepository: Repository) {
        self.productsView = productsView
        self.productsRepository = productsRepository
    }
    
    public func onStart() {
        productsView.show(title: "Products")
        productsView.showLoadingStatus()
        productsRepository.get { [unowned self] retrievedProducts in
            self.tryToShow(retrievedProducts: retrievedProducts)
            self.productsView.hideLoadingStatus()
        }
    }
    
    private func tryToShow(retrievedProducts: [Product]?) {
        if let products = retrievedProducts {
            productsView.show(products: products)
        } else {
            productsView.showErrorWith(message: "No products available")
        }
    }
    
    public func onSelected(product: Product) {
        if product.description != "" {
            productsView.showDetailFor(product: product)
        } else {
            productsView.showErrorWith(message: "Product without description")
        }
    }
}

Develop a class like this one in TDD it’s easy, given the fact that we can mock every dependecies it has and we can test in detail all the presentation flow. The unit test of our presenter are shown below. You can note that a lot of handcraft made mock objects are used but not reported here (you will find them in the complete project on Github reported at the end of this article).

class ProductsPresenterTests: XCTestCase {
    private var productsRepositoryWithProducts: ProductsRepositoryWithProductsSpy!
    private var productsRepositoryWithoutProducts: ProductsRepositoryWithoutProductsSpy!
    private var productsView: ProductsViewSpy!
    private var productPresenter: ProductsPresenter!

    func testOnStartWithProducts() {
        givenAProductsRepositoryWithProducts()
        givenAProductsView()
        givenAProductsPresenterWith(repository: productsRepositoryWithProducts)
        whenTheProductsPresenterStarts()
        thenTheTitleIsDisplayed()
        thenTheProductViewShowsLoadingStatus()
        thenTryToRetrieveProduct()
        thenTheProductViewHidesLoadingStatus()
        thenTheProductsViewShowsTheProducts()
    }
    
    func testOnStartWithoutProducts() {
        givenAProductsRepositoryWithoutProducts()
        givenAProductsView()
        givenAProductsPresenterWith(repository: productsRepositoryWithoutProducts)
        whenTheProductsPresenterStarts()
        thenTheTitleIsDisplayed()
        thenTheProductViewShowsLoadingStatus()
        thenTryToRetrieveProductFromEmptyRepository()
        thenTheProductViewHidesLoadingStatus()
        thenTheProductsViewShowsAnErrorMessage()
    }
    
    func testOnProductWithDescriptionSelected() {
        givenAProductsRepositoryWithProducts()
        givenAProductsView()
        givenAProductsPresenterWith(repository: productsRepositoryWithProducts)
        whenAProductWithDescriptionIsSelected()
        thenTheProductDetailIsShown()
    }
    
    func testOnProductWithoutDescriptionSelected() {
        givenAProductsRepositoryWithProducts()
        givenAProductsView()
        givenAProductsPresenterWith(repository: productsRepositoryWithProducts)
        whenAProductWithoutDescriptionIsSelected()
        thenTheProductsViewShowsAnErrorMessage()
    }
    
    private func givenAProductsRepositoryWithProducts() {
        productsRepositoryWithProducts = ProductsRepositoryWithProductsSpy()
    }
    
    private func givenAProductsRepositoryWithoutProducts() {
        productsRepositoryWithoutProducts = ProductsRepositoryWithoutProductsSpy()
    }
    
    private func givenAProductsView() {
        productsView = ProductsViewSpy()
    }
    
    private func givenAProductsPresenterWith(repository: Repository) {
        productPresenter = ProductsPresenter(productsView: productsView, productsRepository: repository)
    }
    
    private func whenTheProductsPresenterStarts() {
        productPresenter.onStart()
    }
    
    func whenAProductWithDescriptionIsSelected() {
        productPresenter.onSelected(product: Product(name: "Car",
                                                     description: "A beautiful car",
                                                     image: "car"))
    }
    
    func whenAProductWithoutDescriptionIsSelected() {
        productPresenter.onSelected(product: Product(name: "Car",
                                                     description: "",
                                                     image: "car"))
    }
    
    private func thenTheTitleIsDisplayed() {
        XCTAssertTrue(productsView.showTitleHasBeenCalled)
    }
    
    private func thenTryToRetrieveProduct() {
        XCTAssertTrue(productsRepositoryWithProducts.getHasBeenCalled)
    }
    
    private func thenTheProductViewShowsLoadingStatus() {
        XCTAssertTrue(productsView.showLoadingStatusHasBeenCalled)
    }

    private func thenTheProductViewHidesLoadingStatus() {
        XCTAssertTrue(productsView.hideLoadingStatusHasBeenCalled)
    }

    private func thenTheProductsViewShowsTheProducts() {
        XCTAssertTrue(productsView.showProductsHasBeenCalled)
    }
    
    private func thenTryToRetrieveProductFromEmptyRepository() {
        XCTAssertTrue(productsRepositoryWithoutProducts.getHasBeenCalled)
    }
    
    private func thenTheProductsViewShowsAnErrorMessage() {
        XCTAssertTrue(productsView.showsErrorMessageHasBeenCalled)
    }
    
    private func thenTheProductDetailIsShown() {
        XCTAssertTrue(productsView.showDetailForProductHasBeenCalled)
    }
}

It easy to see that the unit tests for our presenter describe the entire presentation flow. This basically means that our unit tests are the documentation of our presentation logic. Cooool!!!! :sunglasses: Now the next big question is: who is going to implement our ProductsView protocol? As we said in the introduction, our view controllers become the View in the Model View Presenter architecture. They act as passive platform specific user interface components updater. This means that our protocol will be implemented by ProductsViewController. It have the responsibility to launch the ProductsPresenter action at the right time and implement all the real passive User Interface update operation. In particular we will have our onStart() presenter method call in the viewDidLoad and the onSelected(product: Product) when a product cell is tapped, that means a product has been selected. The final implementation will be:

class ProductsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, ProductsView {
    @IBOutlet weak var productsTableView: UITableView!
    @IBOutlet weak var productsLoadingView: UIView!
    @IBOutlet weak var productsActivityIndicator: UIActivityIndicatorView!
    private var productsList: [Product]!
    private var productSelected: Product!
    private var productsRepository: ProductsRepository!
    private var productsPresenter: ProductsPresenter!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeDependencies()
        productsPresenter.onStart()
    }
    
    private func initializeDependencies() {
        productsList = []
        productsRepository = ProductsRepository()
        productsPresenter = ProductsPresenter(productsView: self, productsRepository: productsRepository)
    }
    
    //MARK: ProductsView
   
    public func show(title aTitle: String) {
        title = aTitle
    }

    public func showLoadingStatus() {
        productsActivityIndicator.startAnimating()
        productsLoadingView.isHidden = false
    }
    
    public func hideLoadingStatus() {
        productsActivityIndicator.stopAnimating()
        productsLoadingView.isHidden = true
    }
    
    public func show(products: [Product]) {
        productsList = products
        productsTableView.reloadData()
    }
    
    public func showErrorWith(message: String) {
        let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { [unowned self] action in
            self.dismiss(animated: true, completion: nil)
        }))
        present(alert, animated: true, completion: nil)
    }
    
    public func showDetailFor(product: Product) {
        productSelected = product
        performSegue(withIdentifier: "ShowProductDetail", sender: nil)
    }
    
    //MARK: Segue
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let productDetailViewController = segue.destination as? ProductDetailViewController {
            productDetailViewController.product = productSelected
        }
    }
    
    //MARK: UITableView Datasource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return productsList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ProductCell", for: indexPath)
        cell.textLabel?.text = productsList[indexPath.row].name
        return cell
    }
    
    //MARK: UITableView Delegate
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        productsPresenter.onSelected(product: productsList[indexPath.row])
    }
}

You don’t need unit tests for the controller: the presenter unit tests assure that our presentation logic is the one expected. The view controller is only updating iOS specific User Interface components (something we hope Apple tested for us :smirk:). In the same way we developed this components, we can go on and implement our product detail by defining first of all a ProductDetailView:

public protocol ProductDetailView: class {
    func show(title aTitle: String)
    func show(product: Product)
    func showErrorWith(message: String)
}

Then our ProductDetailPresenter presenter, that will be responsible to check that a valid product to show has been received:

public class ProductDetailPresenter {
    private unowned let productDetailView: ProductDetailView
    private let product: Product?
    
    public init(productDetailView: ProductDetailView, product: Product?) {
        self.productDetailView = productDetailView
        self.product = product
    }
    
    public func onStart() {
        productDetailView.show(title: "Product")
        if let product = product {
            productDetailView.show(product: product)
        } else {
            productDetailView.showErrorWith(message: "Product not valid")
        }
    }
}

Its unit tests will be:

class ProductDetailPresenterTests: XCTestCase {
    private var productDetailPresenter: ProductDetailPresenter!
    private var productDetailView: ProductDetailViewSpy!
    
    func testShowDetailOfAProduct() {
        givenAProductDetailView()
        givenAProductDetailPresenterWith(product: Product(name: "aProduct",
                                                          description: "aDescription",
                                                          image: "image"))
        whenThePresenterStarts()
        thenTheTitleIsDisplayed()
        thenTheProductDetailIsShown()
    }
    
    func testShowDetailOfAnInvalidProduct() {
        givenAProductDetailView()
        givenAProductDetailPresenterWith(product: nil)
        whenThePresenterStarts()
        thenTheTitleIsDisplayed()        
        thenAnErrorMessageIsDisplayed()
    }
    
    private func givenAProductDetailView() {
        productDetailView = ProductDetailViewSpy()
    }
    
    private func givenAProductDetailPresenterWith(product: Product?) {
        productDetailPresenter = ProductDetailPresenter(productDetailView: productDetailView, product: product)
    }
    
    private func whenThePresenterStarts() {
        productDetailPresenter.onStart()
    }
    
    private func thenTheTitleIsDisplayed() {
        XCTAssertTrue(productDetailView.showTitleHasBeenCalled)
    }
    
    private func thenTheProductDetailIsShown() {
        XCTAssertTrue(productDetailView.showProductHasBeenCalled)
    }
    
    private func thenAnErrorMessageIsDisplayed() {
        XCTAssertTrue(productDetailView.showErrorHasBeenCalled)
    }
}

....

class ProductDetailViewSpy: ProductDetailView {
    private(set) var showTitleHasBeenCalled: Bool = false
    private(set) var showProductHasBeenCalled: Bool = false
    private(set) var showErrorHasBeenCalled: Bool = false
    
    func show(title aTitle: String) {
        showTitleHasBeenCalled = true
    }
    
    func show(product: Product) {
        showProductHasBeenCalled = true
    }
    
    func showErrorWith(message: String) {
        showErrorHasBeenCalled = true
    }
}

Finally our ProductDetailViewController that is the view controller for this app section:

class ProductDetailViewController: UIViewController, ProductDetailView {
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UILabel!
    @IBOutlet weak var imageView: UIImageView!
    var product: Product!
    private var productDetailPresenter: ProductDetailPresenter!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeDependencies()
        productDetailPresenter.onStart()
    }
    
    private func initializeDependencies() {
        productDetailPresenter = ProductDetailPresenter(productDetailView: self, product: product)
    }
    
    //MARK: ProductDetailView
    
    public func show(title aTitle: String) {
        title = aTitle
    }
    
    public func show(product: Product) {
        nameLabel.text = product.name
        descriptionLabel.text = product.description
        imageView.image = UIImage(named: product.image)
    }
    
    public func showErrorWith(message: String) {
        let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { [unowned self] action in
            self.dismiss(animated: true, completion: nil)
        }))
        present(alert, animated: true, completion: nil)
    }
}

Yeaaaahh you made it!! You’re at the end of this never ending post :satisfied:!!
Now you can start to create your high quality unit tested apps :relieved:. One final note about the implementation above: the productsView property of the ProductsPresenter and productDetailView of the ProductDetailPresenter must be unowned or weak to avoid a retain cycle between the presenters and the controllers.

Model view presenter ios unit tests

Time to try it yourself in one of your project. If you wanna review the complete project code you can check this Github repository.

Phong reflection model

In this post I will talk about phong reflection model: one of the oldest and most popular lighting model in computer graphics.


We live in the era of Physically Based Rendering (PBR). Everyone in the computer graphics field know it is the future. I will talk a lot about it in some future post. But now, for this first post about computer graphics theory, I would like to talk about one of the most popular lighting model used in computer graphics: the Phong reflection post.
Why? Because even if PBR is winning the war (I know you’re scared about PBR theoretical foundation :fearful: :stuck_out_tongue:), the Phong reflection model is still used in a lot of application, and it is also a good starting point for everyone who want to start a journey in the computer graphics field. In this post I will show you what it is in detail and we will see an implementation in OpenGL ES GLSL shading language. All the vectors reported in this article will be normalized. First of all we need to do a classification of the lighting models available in computer graphics. The light at any give point on a surface in a scene is influenced by:

  • Direct illumination: light directly arriving on the surface
  • Indirect illumination: light arriving on the surface after having bounced off other surfaces

As a consequence of this fact lighting methods can be:

  • Local models: only the direct illumination is considered
  • Global models: both direct and indirect illuminations are considered

The Phong reflection model is an empirical (so based on observations) local illumination model. Let’s see how we is it composed. In real world light is modeled by its spectrum, and each surface by its reflectance spectrum. In computer graphics often an approximation based on RGB triplets is used:

  • Light color is a RGB triplet
  • The reflectance spectrum is a triple of percentage

So each component of the following equations will be described by a triplet of number (RGB or percentage).
The light that you see on a surface could be decomposed into four main components. Let’s see them in detail and how they are composed together to calculate the illumination of a surface point: Phong model.

Emissive component

This is the light component emitted by the surface material. Is a purely additive component. As you can image, few surface material in nature are emissive (e.g.: light :laughing:). So the emissive illumination $I_{\text{emissive}}$ of a surface point is obtained by multiplying the emissive constant of a surface $k_{\text{e}}$ by the light emissive intensity $I_{\text{LE}}$ (expressed as we said before as a RGB triplet, and this will be valid for all light intensity define in the following formulas of this post). The emissive light intensity could be the intensity of the scene light (or an average if you have multiple scene lights): pratically speaking you can use the scene light RGB color. The emissive constant $k_{\text{e}}$ is a surface property that express its emissive reflectance.

Ambient component

This is light component used to model empirically the contribution of indirect illumination of bouncing lights in the scene on a surface. It depends entirely on the surface material (no geometry influences). So the ambient illumination $I_{\text{ambient}}$ of a surface point is obtained by multiplying the ambient constant of a surface $k_{\text{a}}$ with the light ambient intensity $I_{\text{LA}}$. The ambient constant $k_{\text{a}}$ is a constant related exclusively to the surface material that express empirically its response to indirect illumination. As for the emissive component, the ambient light intensity could be the intensity of the scene light (or an average if you have multiple scene lights).

Diffusive component

This light component represents the amount of reflected light given an incident light. Lambertian surfaces are considered: The incident light is equally reflected (with a given amount) in all directions. The amount of reflected light depends on the incident angle of the light with respect to the surface’s normal. The diffuse illumination $I_{\text{diffuse}}$ of a surface point is obtained by multiplying the diffuse surface constant $k_{\text{d}}$ with the light diffuse intensity $I_{\text{LD}}$ and with the attenuation factor due to incident light given by the cosine of the angle between the light direction and the surface normal $\cos\theta$. This last value is the dot product between the surface normal ${\hat {N}}$ and the light direction ${\hat {L}}$. So the final formula for the diffuse component is:

Specular component

This light componet represents the amount of reflected light in a specific direction (mirror alike reflection). Light is reflected in a different way depending on the incident light direction. Shiny materials are the one with a high specular component. The perceived specular light depends on the position of the observer with respect to the surface. In particular, the specular illumination is influenced by $\cos\alpha$, that is the cosine of the angle between the direction from the surface point towards the view ${\hat {V}}$ and the direction that a perfectly reflected ray of light would take from this point on the surface ${\hat {R}}$. The size of the specular highlights is regulated by a shininess constant , based on the surface material properties. Given all this information the specular component formula obtained by multiplying the specular surface constant $k_{\text{s}}$ with the light specular intensity $I_{\text{LS}}$ and with dot product of the reflection direction ${\hat {R}}$ and the the direction from the surface point towards the view ${\hat {V}}$ squared to the shininess constant :

The above observation are valid also in case we have multiple lights. The only difference is that the diffuse and specular component are calculated for each light and their sum is the final diffuse and specular component. Now we are ready to write the complete Phong reflection lighting equation:

Just a final note: we distinguished different type of light intensity based on the component. In fact most of the time this model is implemented using a single general light intensity triplet for all the component for each light. How can you implement it in a OpenGL ES shader? The following code sample is a simple implementation of this model using RGB colors. It is a fragment shader that could be used to implement per fragment lighting. This basically means that all lighting calculation is done in the fragment shader on each fragment (maybe this is material for a new post :stuck_out_tongue_closed_eyes:). It was written using OpenGL ES 3.0 and GLSL 3.0. It uses a single light for all the component calculation.

The following image is an example of the happy buddha Stanford mesh rendered using my Spectral BRDF explorer iOS renderer. The lighting is (obviously) calculated using the Phong reflection model. The surface simulated is bronze (you can find some of the constant we discussed before here). Nice :smirk:!!!!

phong example - spectral brdf explorer

A first approach to contract test

In this post I will talk about contract test: what they are and how you can use them.


Sometimes you have to unit test multiple implementations of the same interface. So basically you have the same tests for multiple concrete implementation of the same interface. In a case like this one, contract test could help you save a lot of time. Using contract test you will be able to run the same set of test for different concrete implementations.
How does it work? The main point is to have a template base abstract “ContractTest” test class that incapsulate the logic of the tests using abstract methods that use the base interface of the objects under test. These abstract methods will be implmented in the subclasses of this “ContractTest” class and they will feed the test with a concrete implementation of the interface used in the declaration of the abstract methods.
Let’s see an example to make everything more clear!!!
The example is a standalone Java project that uses Junit 4 and Mockito 2.8, but nothing stops you from applying this concept to other languages/platform (in fact, I learned and implemented contract test on a component inside an Android App :heart_eyes:).
Suppose for example that we have the following interface:

public interface Command {
    void execute();
}

We have two object that implement that interface: AccountCommand and SettingsCommand.

class AccountCommand implements Command {
    private MenuActionsListener menuActionsListener;

    AccountCommand(MenuActionsListener menuActionsListener) {
        this.menuActionsListener = menuActionsListener;
    }

    public void execute() {
        menuActionsListener.onAccountSelected();
    }
}

public class SettingsCommand implements Command {
    private MenuActionsListener menuActionsListener;

    SettingsCommand(MenuActionsListener menuActionsListener) {
        this.menuActionsListener = menuActionsListener;
    }

    public void execute() {
        menuActionsListener.onSettingsSelected();
    }
}

As you can see the two implementations look very similar. So it’s time to rock with contract test :metal:!!!!
We can write a CommandContract base test class that contains the logic of the test we want to write. In our specific case we want to assure that when a command is executed, by calling the execute() method, the menuActionsListener is called with the correct method on each concrete implementation of Command. So our CommandContract implementation is:

abstract class CommandContract {
    private Command command;
    private MenuActionsListener menuActionsListener;

    @Test
    public void commandIsExecuted() throws Exception {
        givenAMenuActionListener();
        command = givenACommand(menuActionsListener);
        whenACommandIsExecuted();
        thenTheCorrectMenuActionIsInvoked(menuActionsListener);
    }

    private void givenAMenuActionListener() {
        menuActionsListener = mock(MenuActionsListener.class);
    }

    protected abstract Command givenACommand(MenuActionsListener menuActionsListener);

    private void whenACommandIsExecuted() {
        command.execute();
    }

    protected abstract void thenTheCorrectMenuActionIsInvoked(MenuActionsListener menuActionsListener);
}

As you can see in the commandIsExecuted() test we use all the abstract method to define the test of generic command implementation. Now in the test subclasses we will implement the abstract method to feed the test with the various implementation of our concrete commands.
So we create an AccountCommandTest class, subclass of CommandContract, to test our AccountCommand class:

public class AccountCommandTest extends CommandContract {

    protected Command givenACommand(MenuActionsListener menuActionsListener) {
        return new AccountCommand(menuActionsListener);
    }

    protected void thenTheCorrectMenuActionIsInvoked(MenuActionsListener menuActionsListener) {
        Mockito.verify(menuActionsListener).onAccountSelected();
    }
}

We create also a SettingsCommandTest class, subclass of CommandContract, to test our AccountCommand class:

public class SettingsCommandTest extends CommandContract {

    protected Command givenACommand(MenuActionsListener menuActionsListener) {
        return new SettingsCommand(menuActionsListener);
    }

    protected void thenTheCorrectMenuActionIsInvoked(MenuActionsListener menuActionsListener) {
        Mockito.verify(menuActionsListener).onSettingsSelected();
    }
}

As you can see we tested all our concrete Command implementations without replicating the unit tests logic. Wonderful :open_mouth::heart_eyes:!!!
Here you can find the complete example (a Maven project developed using IntelliJ, Juni4, Mockito).
It’s time for you to test contract test on your project :joy::laughing:!!!

Swift Closure: demystifying @escaping and @autoclosure attributes

In this post I will talk about Swift closure and the potential of the @escaping and @autoclosure attributes.


As reported in the official swift documentation and as we saw in in one of my previous post, closures are:

self-contained blocks of functionality that can be passed around and used in your code. They can capture and store references to any constants and variables from the context in which they are defined.

In this post I will show you two interesting closure features: @autoclosure and @escaping.
An @escaping closure is passed as a parameter to a function, but it is not executed inside it. So, basically the closure is executed after the function returns. The classical example is a closure being stored in a variable outside that function.
An @autoclosure is a closure without parameter that is automatically created to wrap an expression that’s being passed as an argument to a function. This two attributes combined have great potential. Let’s see an example where you can avoid multiple if/switch with the use of closure and these two attributes.
You could start “abusing” closures and use them everywhere after mastering these two attributes!! :stuck_out_tongue_winking_eye: (Maybe it’s better to stay calm and don’t abuse closures even after seeing this attributes :relieved:).

Swift closure everywhere

For example we can have a UITableView and we want to execute different action for each cell displayed. If we don’t use closure and the attributes @autoclosure and @escaping, we need to distinguish the cells using the position or eventually casting some specialization of a class used to represent the cell data. Suppose instead that each cell shows an instance of an Operation class, defined in this way:

class Operation {
    let name: String
    let action: () -> ()
    
    init(name: String, action: @autoclosure @escaping () -> ()) {
        self.name = name
        self.action = action
    }
}

So, basically in the constructor we are expecting something that will be enclosed in a closure, thanks to the @autoclosure attribute, and we store it as an instance variable of our class. We can store it because we are using also the @escaping attribute. Now in our controller we can define an array of operation that will be the datasource to our UITableViewController. We can pass in the constructor of each Operation instance the function that corresponds to the operation that we want to execute. This function will be executed in the table view delegate method public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) by accessing the corresponding element in the data source array, without the need to identify the exact cell type selected. Here you can find the complete OperationsViewController:

class OperationsViewController: UITableViewController {
    var operations: [Operation] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.operations.append(Operation(name: "Operation 1", action: self.showOrangeDetail()))
        self.operations.append(Operation(name: "Operation 2", action: self.showGreenDetail()))
    }
    
    //MARK: TableView Datasource
    
    public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.operations.count
    }
    
    public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "OperationCell")!
        cell.textLabel?.text = self.operations[indexPath.row].name
        return cell
    }
    
    //MARK: TableView Delegate
    
    public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.operations[indexPath.row].action()
    }
    
    //MARK: Actions
    
    private func showOrangeDetail() {
        self.performSegue(withIdentifier: "OrangeSegue", sender: nil)
    }
    
    private func showGreenDetail() {
        self.performSegue(withIdentifier: "GreenSegue", sender: nil)
    }
}

You can download the complete example here.
So basically: no if, no switch, only love :heart: for @autoclosure and @escaping :heart_eyes:.